<script lang="ts">
	import Divider from '$components/basic/divider/divider.svelte';
	import IconButton from '@smui/icon-button';
	import Card from './_com/card.svelte';
	import Button from '@smui/button';
	import { handleReqMounted } from '@/hooks/handleReq';
	import { page } from '$app/stores';
	import { getValue } from '$utils/get';
	import { goBack, goto } from '$utils/intercept';
	import { API } from '@/api/constant.api';
	import CircularProgress from '@smui/circular-progress';
	import { createMessage } from '$components/basic/message';

	const getParams = () =>
		window.location.search
			.split('?')[1]
			.split('&')
			.reduce((pre, cur) => {
				return { ...pre, [cur.split('=')[0]]: cur.split('=')[1] };
			}, {});

	// console.log($page.url.search.split('=')[1]);
	let current = $page.url.search;
	let detail: Partial<Order.Order> = {};
	const params: Partial<{ id: string; orderno: string }> = getParams();
	const handle = (res) => (detail = res.data);
	const cacheFor = 0;
	const { loading, reqInfo: refresh } = handleReqMounted(() => '/order/detail?id=' + params.id, {
		type: 'get',
		params: { cacheFor },
		handle
	});

	let active: number = -1;
	let list: Partial<Order.Shipment>[] = [];
	const setList = (res) => {
		list = res.data;
		const has = list.findIndex((i) => i.status);
		active = has ? has : active;
	};
	const { loading: loading2, reqInfo: getQuotes } = handleReqMounted(
		() => '/order/ship_history?orderId=' + params.id,
		{
			type: 'get',
			params: { cacheFor },
			handle: setList
		}
	);

	const shippingDetails = [
		{ label: 'Express Company:', value: 'shipCompany' },
		{ label: 'Estimated Shipping Cost:', value: 'shipCost' },
		{ label: 'Reservation Number:', value: '----' }, // Reservation Number is hardcoded
		{ label: 'Delivery Deadline:', value: 'shipDate' },
		{ label: 'Validity Period:', value: 'shipValidity' },
		{ label: 'Packing Form:', value: 'packType' },
		{ label: 'Packing Quantity:', value: 'packNum' },
		{ label: 'Packing Size:', value: 'packInfo' }
	];

	let loading3 = false; // TODO
	const showLoading = () => (loading3 = true);
	const hideLoading = () => (loading3 = false);
	const editQuoteParams = { id: -1, status: 1 };
	const { reqInfo: editQuote } = handleReqMounted(API.ORDER.QUOTE, {
		type: 'post',
		params: editQuoteParams,
		isInit: false
	});
	async function chooseShipQuote(index: number) {
		if (detail.status! > 3)
			return createMessage({ type: 'light', message: 'could not edit quote' });
		const lastIndex = active;
		active = index;
		editShipQuote(index, lastIndex);
	}
	async function editShipQuote(index: number, lastIndex: number) {
		showLoading();
		editQuoteParams.id = list[index].id!;
		await editQuote()?.catch(() => (active = lastIndex));
		await refresh();
		hideLoading();
	}
	function rejectAllQuotes() {
		editQuoteParams.status = 0;
		editShipQuote(active, active)
			.then(() => (active = -1))
			.finally(() => (editQuoteParams.status = 1));
	}

	const viewExpress = () =>
		getValue(detail, 'status') &&
		goto(
			`/order/tracking?orderId=${detail.id}&shipNumber=${getValue(detail, 'express.shipNumber')}`
		);

	$: orderList = detail.order_items ? detail.order_items : []; // TODO
	$: amount = orderList.reduce((pre, cur) => pre + Number(cur.price) * Number(cur.nums), 0);
	$: address = detail.address;
	$: {
		(async () => {
			if ($page.url.search !== current) {
				current = $page.url.search;
				console.log('change');

				await Object.assign(params, getParams());
				console.log(params);
				refresh();
				getQuotes();
			}
		})();
	}
</script>

<div class="w-full flex-cc">
	<div class="w-1320px max-w-100% min-w-350px flex flex-col py-20px gap-15px">
		<div class="w-full flex justify-between items-center bg-gray-2 h-48px pr-10px">
			<Button class="gap-10px h-full" style="--mdc-theme-primary: #6b7280" on:click={goBack}>
				<span class="material-symbols-outlined"> undo </span>
				<span>Back</span>
			</Button>
			<div class="flex-cc gap-10px h-full">
				{#if Number(detail.status) > 4}
					<Button class="gap-10px" variant="raised" on:click={viewExpress}>
						<span>tracking</span>
					</Button>
				{/if}
				<Button
					class="gap-10px"
					style="background-color:#e30000; --mdc-theme-primary: #6b728"
					variant="raised"
					on:click={() => goto('/order/invoice?id=' + params.id)}
				>
					<span>Invoice</span>
				</Button>
			</div>
		</div>
		<Card title="Order Detail" loading={$loading}>
			<li
				class="grid grid-order-table h-32px line-height-32px font-size-16px color-gray-5 bg-white"
			>
				<span class="px-4">ID</span>
				<span class="px-4">Code No.</span>
				<span class="px-4">Item Name</span>
				<span class="px-4">Quantity</span>
				<span class="px-4">UnitPrice</span>
				<span class="px-4">Amount</span>
			</li>
			<Divider style="--mdc-theme-primary: #f3f4f6 " />
			{#each orderList as item, index (getValue(item, 'id'))}
				<li
					class="grid grid-order-table h-32px line-height-32px font-size-16px color-gray-5 bg-white"
				>
					<span class="px-4">{index + 1}</span>
					<span class="px-4">{getValue(item, 'code') + '-' + getValue(item, 'dash', '--')}</span>
					<span class="px-4 whitespace-pre-wrap">{getValue(item, 'title')}</span>
					<span class="px-4">{getValue(item, 'nums')}</span>
					<span class="px-4">$ {getValue(item, 'price')}</span>
					<span class="px-4">$ {getValue(item, 'amount')}</span>
				</li>
			{/each}
		</Card>
		{#if list.length || $loading2}
			<Card title="Shipping Quote" loading={$loading2}>
				<div class="w-full font-size-16px color-gray-5 grid grid-cols-1 gap-4px py-8px px-8px">
					{#each list as item, index}
						<button
							class="border-none p-0 mb-2 outline-none cursor-pointer bg-transparent shadow-md shadow-blue-7 relative flex items-center justify-start h-fit animate-both animate-fade-in-up"
							style={`animation-delay: ${(index + 1) * 250}ms !important; ${active === index ? 'border-color: var(--mdc-theme-primary); color: var(--mdc-theme-primary);' : 'box-shadow: none !important;'}`}
							on:click={() => chooseShipQuote(index)}
						>
							<div class="h-full w-40px font-size-30px color-gray-3">{index + 1}</div>
							<div
								class="text-left indent-0 m-0 bg-transparent w-full grid grid-cols-6 gap-1px w-88% h-fit"
							>
								{#each shippingDetails as ship}
									<div
										class="opacity-80 bg-gray-1 font-size-15px px-1 line-height-32px h-32px"
										style={active === index ? 'background-color: #dbeafe' : ''}
									>
										{ship.label}
									</div>
									<div class="font-size-15px px-1 line-height-32px h-32px">
										{getValue(item, ship.value, '----')}
									</div>
								{/each}
							</div>
							<div
								class="absolute flex-cc w-30px h-30px bottom-10px right-10px font-size-24px"
								style={active === index ? 'display: block' : 'display: none'}
							>
								{#if loading3}
									<CircularProgress
										class="my-four-colors"
										style="height: 24px; width: 24px;"
										indeterminate
										fourColor
									/>
								{:else}
									<span class="material-symbols-outlined"> check </span>
								{/if}
							</div>
						</button>
					{/each}
					<Button
						class="w-full h-30px"
						variant="raised"
						style="--mdc-theme-primary: #9ca3af"
						on:click={rejectAllQuotes}
					>
						<span>Reject All Quotes</span>
					</Button>
				</div>
			</Card>
		{/if}
		<Card title="Shipping Address" loading={$loading}>
			<div
				class="reset-button w-full font-size-16px color-gray-5 bg-white p-20px relative"
				style="box-shadow: 0 1px 4px 0px rgb(0 0 0 / 0.1)"
			>
				<div class="w-full grid grid-cols-3 gap-20px mb-2">
					<div class="flex flex-row items-center gap-10px">
						<span class="material-symbols-outlined">contact_mail</span>
						<span>{address?.fName} {address?.lName}</span>
					</div>

					<div class="flex flex-row items-center gap-10px">
						<span class="material-symbols-outlined">markunread_mailbox</span>
						<span>{address?.postcode}</span>
					</div>

					<div class="flex flex-row items-center gap-10px">
						<span class="material-symbols-outlined">phone_iphone</span>
						<span>{address?.phone}</span>
					</div>
				</div>

				<div class="w-full mb-2 flex flex-row items-center gap-10px">
					<span class="material-symbols-outlined">apartment</span>
					<span>{address?.companyName}</span>
				</div>

				<div class="w-full flex flex-row items-center gap-10px">
					<span class="material-symbols-outlined">local_shipping</span>
					<span
						>{address?.aDetail}, {address?.aCity}, {address?.aProvince}, {address?.aCountry}</span
					>
				</div>

				<!-- <div class="absolute flex-cc w-100px h-100px top-10px right-10px font-size-100px">😊</div> -->
			</div>
		</Card>
		<Card title="Billing Detail" loading={$loading}>
			<div class="w-full bg-red-1 py-30px px-20px font-bold flex gap-2em">
				<span>
					Subtotal: <span class="color-red-7">$ {amount ? amount.toFixed(2) : '---'}</span>
				</span>
				<span
					>Shipping Cost: {detail.shipping != 0
						? '$ ' + Number(detail.shipping).toFixed(2)
						: 'To be Confirm'}</span
				>
				<span>Grand Total: {(Number(detail.shipping) + amount).toFixed(2)}</span>
			</div>
		</Card>

		<div class="w-full flex-cc gap-20px">
			<Button
				class="w-full h-60px"
				variant="raised"
				style={detail.prevId ? '' : '--mdc-theme-primary: #e5e7eb'}
				on:click={() => detail.prevId && goto(`/order/detail?id=${detail.prevId}&refresh=true`)}
			>
				<span class="material-symbols-outlined"> arrow_back_ios </span>
				pre order
			</Button>

			<Button
				class="w-full h-60px"
				variant="raised"
				style={detail.nextId ? '' : '--mdc-theme-primary: #e5e7eb'}
				on:click={() => detail.nextId && goto(`/order/detail?id=${detail.nextId}&refresh=true`)}
				>next order
				<span class="material-symbols-outlined">arrow_forward_ios</span>
			</Button>
		</div>
	</div>
</div>

<style>
	/* .button-box:hover {
		filter: contrast(0.8);
	}
	.button-box:active {
		filter: brightness(0.8);
	} */
	.grid-order-table {
		grid-template-columns: 1fr 1fr 4fr 1fr 1fr 1fr;
	}
</style>
